package com.yuandian.resolver;

import cn.hutool.core.util.StrUtil;
import com.yuandian.enums.S;
import org.springframework.util.PropertyPlaceholderHelper;

import java.util.List;
import java.util.Map;

/**
 * 说明：&模板替换器
 * @Author zfsn
 * @Date 2023/2/17 11:32
 */
public class IsNotEmptyResolver implements PropertyPlaceholderHelper.PlaceholderResolver {

	private final Map<String, Object> req;

	public IsNotEmptyResolver(Map<String, Object> req) {
		this.req = req;
	}

	@Override
	public String resolvePlaceholder(String placeholderName) {
		String[] operators = placeholderName.split(S.SPLIT_QUESTION.s());
		String key = operators[0].trim();
		String replaceStr = operators[1].trim();
		String[] replaces = replaceStr.split(S.COLON.s());
		String case1 = replaces[0];
		String case2 = replaces.length >= 2 ? replaces[1] : S.BLANK.s();
		Object value = req.get(key);
		if (value == null) {
			return case2;
		} else if (value instanceof List) {
			if (((List<?>) value).isEmpty()) {
				return case2;
			}
		} else if (value instanceof String && StrUtil.isEmpty((String) value)) {
			return case2;
		}
		return case1;
	}
}
